package alf.mapping.view.touch;

import alf.mapping.view.Env;
import alf.mapping.view.visuals.EditorEngine;
import alf.mapping.view.visuals.Sprite;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.MotionEvent;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractTouchReactor 
implements TouchReactor {

	protected Context ctx;

	protected TouchReactorCallback callback;
	protected EditorEngine editor = EditorEngine.getInstance();
	
	protected static final int DISTANCIA_SEL = 40;
	protected static final int MOVING_STEP = 10;

	protected Object oldSel;

	protected long oldSelTime;

	public void setCallback(TouchReactorCallback callback) {
		this.callback = callback;
	}

	public void setCtx(Context ctx) {
		this.ctx = ctx;
	}

	public boolean onTouchEvent(MotionEvent event) {
		//posicion tocada
	//	boolean result = true;
	//	EditorEngine.Mode mode = editor.getMode();
		Point p =new Point((int) event.getX(), (int) event.getY());
		Rect r = getPuntoGordo(p);
		callback.setTouchArea(new Rect(r));
		return onTouch(event,p,r);
	}
	
	protected boolean onTouch(MotionEvent event, Point punto, Rect puntogordo) {
		return true;
	}
	
	protected Rect getPuntoGordo(Point p) {
		Rect r = new Rect(p.x, p.y, p.x, p.y);
		r.inset(-DISTANCIA_SEL, -DISTANCIA_SEL);
		return editor.scr2model(r);
	}
	
	protected Sprite spriteAtPos(Rect puntoGordo) {
		for (Sprite sprite : editor.getSprites()) {
			if (Rect.intersects(sprite.rect(), puntoGordo)) {
				return sprite;
			}
		}
		return null;
	}
	

	public static int distance(Rect r) {
		return (int)Math.sqrt((double)r.width() * (double)r.width()
							  + (double)r.height() * (double)r.height());
	}

	protected float zoomFactor() {
		return 100f / editor.getZoom();
	}

	protected List<Sprite> spritesAtRect(Rect r) {
		List<Sprite> list = null;
		Rect itemRect;
		Env.debug("spritesAtRect(" + r + ")");
		for (Sprite sprite : editor.getSprites()) {
			itemRect = sprite.rect();
			if (r.contains(itemRect) || Rect.intersects(itemRect,r)) {
				Env.debug("rect+:" + sprite.rect());
				if (list == null) {
					list = new ArrayList<Sprite>();
				}
				list.add(sprite);
			} else {
			Env.debug("rect-:" + sprite.rect() +"("+r.contains(itemRect)+","+r.intersect(itemRect)+")");
			}
		}
		return list;
	}
	
	protected boolean detectDoubleTap(Sprite sel) {
		final long now = SystemClock.elapsedRealtime();
		return sel != null && sel.equals(oldSel) && (now - oldSelTime) < 600;
	}
}
